<template>
  <div>
    <h1>计算属性和监听</h1>
    <input type="text" v-model="user.firstName" /><br />
    <input type="text" v-model="user.lastName" /><br />
    <input type="text" v-model="user.child.lastName" /><br />
    <input type="text" v-model="fullName1" /><br />
    <input type="text" v-model="fullName2" /><br />
    <input type="text" v-model="fullName3" /><br />
    <input type="text" v-model="fullName4" />
  </div>
</template>
<script lang="ts">
import {
  computed,
  defineComponent,
  reactive,
  ref,
  watch,
  watchEffect,
} from "vue";

export default defineComponent({
  setup() {
    const user = reactive({
      firstName: "zheshu",
      lastName: "li",
      child: {
        firstName: "xiaozheshu",
        lastName: "xiaoli",
      },
    });
    const fullName1 = computed(() => {
      return user.firstName + "-" + user.lastName;
    });
    console.log(fullName1);
    const fullName2 = computed({
      get() {
        return user.firstName + "-" + user.lastName;
      },
      set(value: string) {
        console.log(value);
        const arr = value.split("-");
        user.firstName = arr[0];
        user.lastName = arr[1];
      },
    });

    const fullName3 = ref("");
    watch(
      [fullName3, () => user.firstName, () => user.lastName],
      (values, oldVaules) => {
        console.log(values);
        console.log(oldVaules);
        if (values[1] != oldVaules[1] || values[2] != oldVaules[2]) {
          fullName3.value = values[1] + "-" + values[2];
        } else if (values[0] != oldVaules[1]) {
          let arr = values[0].split("-");
          user.firstName = arr[0];
          user.lastName = arr[1];
        }
      }
    );

    const fullName4 = ref("");
    watchEffect(() => {
      fullName4.value = user.firstName + "-" + user.lastName;
    });

    return {
      user,
      fullName1,
      fullName2,
      fullName3,
      fullName4,
    };
  },
});
</script>

<style scoped>
</style>